﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NPMonitor.Interfaces;
using NPMonitor.Implementation.Store;
using System.Collections.ObjectModel;
using NPMonitor.DataModel;
using System.Configuration;
using NPMonitor.Web.Code;
using NPMonitor.Implementation;
using System.Web.UI;
using System.IO;
using Newtonsoft.Json;

namespace NPMonitor.Web.Handler
{
    /// <summary>
    /// MachinesHandler 的摘要说明
    /// </summary>
    public class MachinesHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            string requestType = context.Request.Params["RequestType"];
            switch (requestType.Trim())
            {
                case "MachineStatus":
                    GetMachineList(context);
                    break;
                case "JobScheduleStatus":
                    GetJobScheduleList(context);
                    break;
            }   

        }

        public void GetMachineList(HttpContext context)
        {
            string poolId = context.Request.Params["PoolId"];
            string pageIndex = context.Request.Params["PageIndex"];
            string pageSize = context.Request.Params["PageSize"];
            ReadOnlyCollection<MachineData> list;
            //所有机器
            if (string.IsNullOrWhiteSpace(poolId))
            {
                int machineTotalCount = StoreManager.Current.MachineStore.GetAllMachinesTotalCount();
                list = StoreManager.Current.MachineStore.GetAllMachines(Convert.ToInt32(pageIndex), Convert.ToInt32(pageSize));
            }
            else
            {
                //根据pool id 获取机器
                int intPoolId = Convert.ToInt32(poolId);
                int machineTotalCount = StoreManager.Current.MachineStore.GetAllMachinesTotalCountByPoolId(intPoolId);
                list = StoreManager.Current.MachineStore.GetMachinesByPoolId(intPoolId, Convert.ToInt32(pageIndex), Convert.ToInt32(pageSize));
            }

            List<MachineInfo> result = new List<MachineInfo>();
            if (list.Count > 0)
            {
                foreach (MachineData data in list)
                {
                    MachineInfo info = new MachineInfo();
                    info.MachineId = data.MachineId;
                    info.MachineStatus = data.Connectivity;
                    info.LastHeartbeat = data.LastHeartbeat.Value.ToString(CommonString.DataTimeFormat);
                    info.ScheduleJobStatusColor = data.TrafficLight;
                    result.Add(info);
                }
            }
            System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
            string strResult = js.Serialize(result);
            context.Response.Write(strResult);
        }

        public void GetJobScheduleList(HttpContext context)
        {
            string machineName = context.Request.Params["MachineName"];
            string pageIndex = context.Request.Params["PageIndex"];
            string pageSize = context.Request.Params["PageSize"];

            int intPageIndex = 0;
            int intPageSize = 12;
            int.TryParse(pageIndex, out intPageIndex);
            int.TryParse(pageSize, out  intPageSize);

            int itemCount = 0;
            ReadOnlyCollection<JobData> jobList = StoreManager.Current.JobStore.GetJobsByMachineName(machineName, intPageIndex, intPageSize, out itemCount);
            List<object> result = jobList.Select(p => new
            {
                Status = p.Status.ToString(),
                Id = p.Id,
                ScheduleRunningType = p.ScheduleRunningType,
                LastStartTime = p.LastStartTime.HasValue ? p.LastStartTime.Value.ToString(CommonString.DataTimeFormat) : "",
                //LastEndTime = p.LastEndTime.HasValue ? p.LastEndTime.Value.ToString(CommonString.DataTimeFormat) : "",
                NextStartTime = p.NextStartTime.HasValue ? p.NextStartTime.Value.ToString(CommonString.DataTimeFormat) : ""
            }).ToList<object>();

            System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
            string strResult = js.Serialize(result);
            context.Response.Write(strResult);
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

    public class MachineInfo
    {
        public int MachineId { get; set; }
        public string MachineStatus { get; set; }
        public string LastHeartbeat { get; set; }
        public string ScheduleJobStatusColor { get; set; }
    }
}